// pages/foodrecord/foodrecord.js
const tabService = require("../../utils/tab-service");

var app = getApp();

Page({
  /**
   * 页面的初始数据
   */
  data: {
    meals: ['breakfast', 'lunch', 'dinner', 'snack'],
    mealNames: {
      breakfast: '早餐',
      lunch: '午餐',
      dinner: '晚餐',
      snack: '加餐'
    },
    dietInfo: {
      breakfast: undefined,
      lunch: undefined,
      dinner: undefined,
      snack: undefined
    },
    date: formatDate(new Date()), // 使用自定义函数格式化当前时间
    dateVisible: false,
    second: undefined, // 使用自定义函数格式化当前时间
  },
  showPicker(e) {
    const {
      mode
    } = e.currentTarget.dataset; // 从事件对象中获取模式值
    this.setData({
      mode,
      [`${mode}Visible`]: true,
    });
  },
  hidePicker() {
    const {
      mode
    } = this.data;
    this.setData({
      [`${mode}Visible`]: false,
    });
  },
  onConfirm(e) {
    const {
      value
    } = e?.detail;
    const {
      mode
    } = this.data;
    this.setData({
      [mode]: value,
    });
    this.setData({
      dietInfo: {}
    })
    this.getTodayDiets();
    this.hidePicker();
  },
  onColumnChange(e) {
    console.log('pick', e?.detail?.value);
  },
  updatePositions() {
    const { meals, dietInfo } = this.data;
    let hasInfoCount = 0;
    let firstNoInfoTop = 0;
    
    // Calculate the number of has-info items
    meals.forEach(meal => {
      if (dietInfo[meal]) {
        hasInfoCount++;
      }
    });

    console.log('dietInfo',dietInfo)

    // Set the initial position for the first no-info item
    firstNoInfoTop = hasInfoCount * 150 + 150; // 100为has-info的高度，需根据实际调整

    dietInfo.forEach(meal=>{
      let topPosition = 0;
      if (!dietInfo[meal]) {
        topPosition = firstNoInfoTop;
        firstNoInfoTop += 50; // 每个no-info间隔50px
      }
      dietInfo[meal].top = topPosition;
    })

    // // Update the positions
    // const updatedMeals = meals.map((meal, index) => {
    //   let topPosition = 0;
    //   if (!dietInfo[meal]) {
    //     topPosition = firstNoInfoTop;
    //     firstNoInfoTop += 50; // 每个no-info间隔50px
    //   }
    //   return {
    //     name: meal,
    //     top: topPosition
    //   };
    // });

    this.setData({
      dietInfo: dietInfo
    });
  },
  // 跳转到添加饮食界面
  goDetailPage(e) {
    const meal = e.currentTarget.dataset.meal;
    wx.navigateTo({
      url: `/pages/foodrecorddetail/foodrecorddetail?param1=${meal}`,
    });
  },
  // 根据时间戳判断是早餐、午餐还是晚餐
  getMealType(timestamp) {
    const date = new Date(timestamp * 1000); // 将秒级时间戳转换为毫秒级
    const hour = date.getHours();

    if (hour >= 6 && hour < 10) {
      return 'breakfast';
    } else if (hour >= 11 && hour < 14) {
      return 'lunch';
    } else if (hour >= 16 && hour < 20) {
      return 'dinner';
    } else {
      return 'snack';
    }
  },
  // 获取今日内所有饮食信息
  getTodayDiets() {
    const {
      protocol,
      host
    } = app.globalData;
    const dietsUrl = `${protocol}://${host}/bgmp/api/diet?Action=GetBetween`;

    // 获取今日零点的时间戳
    const begin = new Date(this.data.date);
    begin.setHours(0, 0, 0, 0);
    const beginTimestamp = begin.getTime();

    // 获取今天23:59:59的时间戳
    const end = new Date(this.data.date);
    end.setHours(23, 59, 59, 999); // 注意这里的毫秒设置为999，以确保是今天的最后一毫秒
    const endTimestamp = end.getTime();

    console.log(begin, end);

    // 更新 timePeriod 对象
    const timePeriod = {
      "begin": Math.floor(beginTimestamp / 1000), // 使用 Math.floor 舍弃小数部分
      "end": Math.floor(endTimestamp / 1000),
    };

    // 输出修改后的 timePeriod 对象
    // console.log(timePeriod);

    wx.request({
      url: dietsUrl,
      method: 'POST',
      header: {
        "Content-Type": "application/json",
        "x-api-key": wx.getStorageSync('token')
      },
      data: timePeriod,
      success: (res) => {
        if (res.data.code === 200) {
          console.log("diet got successfully", res);
          const diets = res.data.message;
          diets.forEach(diet => {
            // const mealType = this.getMealType(diet.time);
            const mealType = diet.type;
            // console.log(mealType);
            const comment = diet.comment;
            const minute = formatTime(new Date(diet.time * 1000))
            const dietImgUrl = `${protocol}://${host}/bgmp/api/files/download?Sid=${diet.picId}`;

            var proteinMass = 0;
            var carbohydratesMass = 0;
            var fatMass = 0;
            // 循环遍历每个食物的营养信息
            const foods = diet.foods;
            // console.log(foods);
            if (foods !== null) {
              foods.forEach(food => {
                food.nutrition.forEach(nutrient => {
                  // 去除单位 "g"，然后将营养质量值转换为数值类型
                  const value = parseFloat(nutrient.value.replace('g', '')); // 将字符串转换为浮点数
                  // 根据关键字判断营养素类型，并累加到相应的质量变量中
                  switch (nutrient.key) {
                    case "蛋白质":
                      proteinMass += value;
                      break;
                    case "碳水化合物":
                      carbohydratesMass += value;
                      break;
                    case "脂肪":
                      fatMass += value;
                      break;
                    default:
                      // 其他情况忽略
                      break;
                  }
                });
              })
              // 修改dietInfo
              this.data.dietInfo[mealType] = {
                comment: comment,
                minute: minute,
                dietImgUrl: dietImgUrl,
                proteinMass: parseFloat(proteinMass.toFixed(1)),
                carbohydratesMass: parseFloat(carbohydratesMass.toFixed(1)),
                fatMass: parseFloat(fatMass.toFixed(1))
              }
              this.setData({
                dietInfo: this.data.dietInfo
              })
              console.log(this.data.dietInfo);
            }
          })
        } else {
          console.log("diet got failed", res);
        }
      },
      fail: (res) => {
        console.log("diet got unsuccessfully", res);
      },
      complete:()=>{
        // this.updatePositions();
      }
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    if (typeof this.getTabBar === 'function' && this.getTabBar()) {
      this.getTabBar().setData({
        selected: 0
      })
    }
    this.getTodayDiets();
    // this.updatePositions();
  },
})


function formatDate(date) {
  var year = date.getFullYear();
  var month = padZero(date.getMonth() + 1); //月份是从0开始的
  var day = padZero(date.getDate());
  return year + '-' + month + '-' + day;
}

// 自定义函数，格式化日期时间
function formatTime(date) {
  var hours = date.getHours();
  var minutes = padZero(date.getMinutes());
  // var seconds = padZero(date.getSeconds());
  // console.log(date)
  return hours + ':' + minutes;
}

// 自定义函数，补零
function padZero(num) {
  return (num < 10 ? '0' : '') + num;
}